/**
 * Created by lbs on 2017/3/9.
 */
var loginApp = angular.module('login', []);

loginApp.factory('UserInfo', ['$http', '$q', function ($http, $q) {
    return {
        post: function (url, data) {
            var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
            $http({
                method: 'POST', url: url, data: data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).error(function (data, status, headers, config) {
                deferred.reject(data);
            });
            return deferred.promise;
        }
    };
}]);

loginApp.controller('loginCtrl', ['$scope', 'UserInfo', function ($scope, UserInfo) {

    $scope.formData = {
        code: '0'
    };

    $scope.btn_login = function () {
        if (!$scope.formData.username || !$scope.formData.password) {
            layer.msg('用户名或者密码不能为空!');
        } else {
            var reqUrl = '',
                //url = window.location.origin;
                url = window.location.href;
            if(url.indexOf('test') > 0){
                //reqUrl = url+'/dm';
                reqUrl = 'http://101.37.32.213:18080/dm';
            }else{
                //reqUrl = 'http://101.37.32.213:18080/dm';
                reqUrl = 'http://101.37.32.213/dm';
            }
            var promise = UserInfo.post(reqUrl+'/management/admin/login', $scope.formData);
            promise.then(function (data) {
                if (data.result == true) {
                    window.location.href = 'index.html';
                    localStorage.setItem('role', data.data.role);
                    localStorage.setItem('name', data.data.name);
                    localStorage.setItem('workId', data.data.workId);
                    localStorage.setItem('token',data.data.token);
                } else {
                    alert(data.message);
                }
            }, function (data) {

            })
        }
    }

    $(document).keypress(function(e) {
        // 回车键事件
        if(e.which == 13) {
            $scope.btn_login();
        }
    });
}])